package main

import (
	"fmt"
	"time"
)

func getChannel() chan int {
	v := make(chan int)
	go func() {
		i := 0
		for {
			v <- i
			i++
			time.Sleep(1 * time.Second)
		}
	}()
	return v
}
func toWork(c chan int) {
	for i := range c {
		time.Sleep(3 * time.Second)
		fmt.Printf("goroutine get %d\n", i)
	}

}

func main() {
	c1 := getChannel()
	c2 := getChannel()

	c := make(chan int)

	go toWork(c)

	var values []int

	// time.After表示再固定时间后传入值
	time := time.After(10 * time.Second)
	for {
		var activeC chan int
		var activeValue int
		if len(values) > 0 {
			activeC = c
			activeValue = values[0]
		}
		// 使用select进行调度
		select {
		case n := <-c1:
			values = append(values, n)
		case n := <-c2:
			values = append(values, n)
		case activeC <- activeValue:
			values = values[1:]

		case <-time:
			fmt.Println("bye")
			return
		}
	}

}
